﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PriceWatcher
{
    public partial class frmNewTarget : Form
    {
        public Target target=null;
        public frmNewTarget()
        {
            InitializeComponent();
        }

        private void txtUrl_Enter(object sender, EventArgs e)
        {
            frmWeb dlg = new frmWeb();
            dlg.newTarget += onReturnNewTarget;
            dlg.ShowDialog();
        }

        public void onReturnNewTarget(object o, NewTargetEventArgs e)
        {
            txtUrl.Text = e.url;
            txtIndex.Text = e.index.ToString();
            txtPrice.Text = e.price.ToString();
        }

        private void butOK_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"http(s?)://(\S)+", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex reg2 = new System.Text.RegularExpressions.Regex(@"^[-+]?[0-9]*.?[0-9]+$");
            if (string.IsNullOrEmpty(txtName.Text))
                errorProvider1.SetError(txtName, "目标名称不能为空");
            else if (!reg1.IsMatch(txtUrl.Text))
                errorProvider1.SetError(txtUrl, "网址的格式错误");
            else if (Convert.ToInt32(txtIndex.Text) < 0)
                errorProvider1.SetError(txtIndex, "目标标识输入有误");
            else if (!reg2.IsMatch(txtPrice.Text))
                errorProvider1.SetError(txtPrice, "目标价格输入有误");
            else
            {
                Target t = new Target();
                t.TargetName = txtName.Text;
                t.TargetURL = txtUrl.Text;
                t.TargetIndex = Convert.ToInt32(txtIndex.Text);
                t.TargetPrice = Convert.ToDecimal(txtPrice.Text);
                target = t;
                Close();
            }            
        }

        private void butCancel_Click(object sender, EventArgs e)
        {
            target = null;
            this.Close();
        }

        private void frmNewTarget_Load(object sender, EventArgs e)
        {
            if (target != null)
            {
                txtName.Text = target.TargetName;
                txtUrl.Text = target.TargetURL;
                txtIndex.Text = target.TargetIndex.ToString();
                txtPrice.Text = target.TargetPrice.ToString();
            }
        }
    }
}